package me.zhengjie.agvSend;

import lombok.RequiredArgsConstructor;
import me.zhengjie.config.IdWorker;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.NestingMiddleTable;
import me.zhengjie.pojo.entity.WcsAgvId;
import me.zhengjie.pojo.entity.WcsInboundMission;
import me.zhengjie.pojo.vo.AgvTaskSubmitVo;
import me.zhengjie.pojo.vo.TaskSubmitData;
import me.zhengjie.sqlservilce.IwsStoreOutsideService;
import me.zhengjie.sqlservilce.NestingMiddleTableService;
import me.zhengjie.sqlservilce.WcsAgvIdService;
import me.zhengjie.sqlservilce.WcsInboundMissionService;
import me.zhengjie.util.state.Manufacturer;
import me.zhengjie.util.state.TaskStatus;
import me.zhengjie.util.state.TaskType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AgvSendServiceImpl implements AgvSendService{
    private static final Logger haikang = LoggerFactory.getLogger("haiKang");

    private final RestTemplate restTemplate;

    private final WcsAgvIdService wcsAgvIdService;

    private final IdWorker idWorker;

    private final WcsInboundMissionService wcsInboundMissionService;

    private final NestingMiddleTableService nestingMiddleTableService;

    private final IwsStoreOutsideService iwsSOutsideService;


    @Override
    public String agvTaskSubmit(AgvTaskSubmitDto agvTaskSubmitDto) {
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<AgvTaskSubmitDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(agvTaskSubmitDto, httpHeaders);
//        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/task/submit";
        String url = ip + "/rcs/rtas/api/robot/controller/task/submit";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康请求参数：{}，请求地址：{},返回结果：{}",agvTaskSubmitDto,url,agvTaskSubmitVo);
        String code = agvTaskSubmitVo.getCode();
        if ("SUCCESS".equals(code)) {
            //消息发送成功
            TaskSubmitData data = (TaskSubmitData) agvTaskSubmitVo.getData();
            String robotTaskCode = data.getRobotTaskCode();
            //消息发送成功，修改任务状态
            return robotTaskCode;
        }
        return null;
    }

    //{
    //  "triggerCode" : "A02",
    //  "robotTaskCode" : "125465fd",
    //  "triggerType" : "SITE",
    //  "targetRoute" : {
    //    "code" : "A02",
    //    "type" : "SITE",
    //    "seq" : 1
    //  }
    //}
    @Override
    public boolean taskContinueExecute(AGVTaskContinueExecuteDto agvTaskContinueExecuteDto) {
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<AGVTaskContinueExecuteDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(agvTaskContinueExecuteDto, httpHeaders);
        String url = ip +"/rcs/rtas/api/robot/controller/task/extend/continue";
//        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/task/extend/continue";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康任务继续执行请求参数：{}，请求地址：{},返回结果：{}",agvTaskContinueExecuteDto,url,agvTaskSubmitVo);
        String code = agvTaskSubmitVo.getCode();
        if ("SUCCESS".equals(code)) {
            //消息发送成功
            TaskSubmitData data = (TaskSubmitData) agvTaskSubmitVo.getData();
            //中间点上报，占用储位
            iwsSOutsideService.updateStatus(TaskType.ONE_FLOOR_RETURN_TO_STORAGE_LOCATION.getMessage(),null,0);
            //消息发送成功，修改任务状态
            return true;
        }
        return false;
    }

    @Override
    public boolean noticeAgv(NoticeAgvDto noticeAgvDto) {
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<NoticeAgvDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(noticeAgvDto, httpHeaders);
        String url = ip +"/rcs/rtas/spi/wcs/robot/eqpt/notify";
//        String url = "http://192.168.3.23:80/rcs/rtas/spi/wcs/robot/eqpt/notify";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康对接外设请求参数：{}，请求地址：{},返回结果：{}",noticeAgvDto,url,agvTaskSubmitVo);
        if ("SUCCESS".equals(agvTaskSubmitVo.getCode())){
            return true;
        }
        return false;
    }

    @Override
    public AgvTaskSubmitVo taskCancel(TaskCancelDto taskCancelDto) {
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<TaskCancelDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(taskCancelDto, httpHeaders);
        String url = ip +"/rcs/rtas/spi/wcs/robot/eqpt/notify";
//        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/task/cancel";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康对接外设请求参数：{}，请求地址：{},返回结果：{}",taskCancelDto,url,agvTaskSubmitVo);
        return agvTaskSubmitVo;
    }

    @Override
    public AgvTaskSubmitVo carrierUnbind(CarrierUnbindDto carrierUnbindDto){
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<CarrierUnbindDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(carrierUnbindDto, httpHeaders);
        String url = ip +"/rcs/rtas/spi/wcs/robot/eqpt/notify";
//        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/site/bind";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康栈板绑定或解绑请求参数：{}，请求地址：{},返回结果：{}",carrierUnbindDto,url,agvTaskSubmitVo);
        return agvTaskSubmitVo;
    }

    @Override
    public boolean regionControl(RegionControlDto regionControlDto) {
        WcsAgvId wcsAgvId = wcsAgvIdService.selectName(Manufacturer.HAIKANG.getManufacturer());
        String ip = wcsAgvId.getIp();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<RegionControlDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(regionControlDto, httpHeaders);
        String url = ip +"/rcs/rtas/api/robot/controller/zone/pause";
//        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/site/bind";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送区域暂停或继续执行：{}，请求地址：{},返回结果：{}",regionControlDto,url,agvTaskSubmitVo);
        if ("SUCCESS".equals(agvTaskSubmitVo.getCode())){
            return true;
        }
        return false;
    }

    @Override
    public AgvTaskSubmitVo dingsheng(DingshengDto dingshengDto) {
        CarrierUnbindDto carrierUnbindDto = new CarrierUnbindDto();
        carrierUnbindDto.setCarrierCategory("PALLET");
        carrierUnbindDto.setSlotCode(dingshengDto.getTargetRoute().get(0).getCode());
        carrierUnbindDto.setInvoke("BIND");
        Integer invoke = dingshengDto.getInvoke();
        List<TargetRoute> targetRoute = dingshengDto.getTargetRoute();
        if (invoke == 1 ){
            carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
            carrierUnbindDto.setCarrierType("1");
        }else if (invoke == 2){
            carrierUnbindDto.setSlotCategory(TaskType.STORAGE.getMessage());
            carrierUnbindDto.setCarrierType("1");
        }else if (invoke == 3){
            carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
            carrierUnbindDto.setCarrierType("2");
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<CarrierUnbindDto> agvTaskSubmitDtoHttpEntity = new HttpEntity<>(carrierUnbindDto, httpHeaders);
//        String url = ip +"/spi/wcs/robot/eqpt/notify";
        String url = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/site/bind";
        AgvTaskSubmitVo agvTaskSubmitVo = restTemplate.postForObject(url, agvTaskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康栈板绑定参数：{}，请求地址：{},返回结果：{}",carrierUnbindDto,url,agvTaskSubmitVo);

        String inboundCode = String.valueOf(idWorker.nextId());
        AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
        agvTaskSubmitDto.setRobotTaskCode(inboundCode);
        agvTaskSubmitDto.setInitPriority(90);
        agvTaskSubmitDto.setTaskType(dingshengDto.getTaskType());
        agvTaskSubmitDto.setTargetRoute(dingshengDto.getTargetRoute());
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-lr-request-id",String.valueOf(idWorker.nextId()));
        HttpEntity<AgvTaskSubmitDto> taskSubmitDtoHttpEntity = new HttpEntity<>(agvTaskSubmitDto, headers);
        String url1 = "http://192.168.3.23:80/rcs/rtas/api/robot/controller/task/submit";
//        String url = ip + "/api/robot/controller/task/submit";
        AgvTaskSubmitVo submitVo = restTemplate.postForObject(url1, taskSubmitDtoHttpEntity, AgvTaskSubmitVo.class);
        haikang.info("发送海康请求参数：{}，请求地址：{},返回结果：{}",agvTaskSubmitDto,url,submitVo);
        String code = submitVo.getCode();
        if ("SUCCESS".equals(code)) {
            //消息发送成功
            List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode("C00083");
            WcsInboundMission wcsInboundMission = new WcsInboundMission();
            wcsInboundMission.setInboundCode(inboundCode);
            wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
            wcsInboundMission.setContainerCode("C00083");
            wcsInboundMission.setSource(targetRoute.get(0).getCode());
            wcsInboundMission.setDestination(targetRoute.get(1).getCode());
            wcsInboundMission.setContainerType(TaskType.PALLET.getStatus());
            wcsInboundMission.setCreateTime(LocalDateTime.now());
            wcsInboundMission.setUpdateTime(LocalDateTime.now());
            wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
            wcsInboundMission.setIsNest(0);
            wcsInboundMission.setIsPlc(0);
            StringBuilder sb = new StringBuilder();
            List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
            for (String materialCode : materialCodeList) {
                if (sb.length() >0){
                    sb.append(",");
                }
                sb.append(materialCode);
            }
            String materIalCode = sb.toString();
            wcsInboundMission.setMaterialCode(materIalCode);
            boolean b = wcsInboundMissionService.insertInbound(wcsInboundMission);
            if (!b) {
                haikang.info("创建入库任务失败");
                throw new RuntimeException("创建入库任务失败");
            }
            //消息发送成功，修改任务状态
            return AgvTaskSubmitVo.OK("下发成功");
        }
        return AgvTaskSubmitVo.ng("任务下发失败");
    }
}
